<template>
  <div class="add-card">
    <header class="add-header">
      <el-page-header :content="title" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">车辆信息</div>
        <div class="form">
          <el-form ref="carInfoForm" :model="carInfoForm" :rules="carInfoRules" label-width="100px">
            <el-form-item label="车主姓名" prop="personName">
              <el-input v-model="carInfoForm.personName" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input v-model="carInfoForm.phoneNumber" />
            </el-form-item>
            <el-form-item label="车辆号码" prop="carNumber">
              <el-input v-model="carInfoForm.carNumber" />
            </el-form-item>
            <el-form-item label="车辆品牌" prop="carBrand">
              <el-input v-model="carInfoForm.carBrand" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-container">
        <div class="title">最新一次月卡缴费信息</div>
        <div class="form">
          <el-form ref="feeForm" :model="feeForm" :rules="feeFormRules" label-width="100px">
            <el-form-item label="有效日期" prop="payTime">
              <el-date-picker
                v-model="feeForm.payTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item label="支付金额" prop="paymentAmount">
              <el-input v-model="feeForm.paymentAmount" />
            </el-form-item>
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="feeForm.paymentMethod">
                <el-option
                  v-for="item in payMethodList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="confirmAdd">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { createCardAPI, getCardDetailAPI, updateCardAPI } from '@/api/user'

export default {
  data() {
    // 车牌号校验规则
    const validateCarNumber = (rule, value, callback) => {
      // 定义车牌号的正则表达式（根据实际需求调整）
      const plateNumberRegex = /^[\u4E00-\u9FA5][A-Z][A-Z0-9]{4}[A-Z0-9挂学警港澳]?$/
      if (!value) {
        callback(new Error('请输入车牌号码'))
      } else if (!plateNumberRegex.test(value)) {
        callback(new Error('车牌号码格式不正确，请输入有效的车牌号码'))
      } else {
        callback()
      }
    }
    return {
      carInfoForm: {
        personName: '', // 车主姓名
        phoneNumber: '', // 车主电话
        carNumber: '', // 车牌号码
        carBrand: '' // 车牌品牌
      },
      carInfoRules: {
        personName: [{ required: true, message: '请输入车主姓名', trigger: 'blur' }],
        phoneNumber: [{ required: true, message: '请输入车主电话', trigger: 'blur' }],
        carNumber: [
          { required: true, message: '请输入车牌号码', trigger: 'blur' },
          { validator: validateCarNumber, trigger: 'blur' }
        ],
        carBrand: [{ required: true, message: '请输入车牌品牌', trigger: 'blur' }]
      },
      feeForm: {
        payTime: '', // 支付时间
        paymentAmount: null, // 支付金额
        paymentMethod: '' // 支付方式
      },
      feeFormRules: {
        payTime: [
          {
            required: true,
            message: '请选择支付时间'
          }
        ],
        paymentAmount: [
          {
            required: true,
            message: '请输入支付金额',
            trigger: 'blur'
          }
        ],
        paymentMethod: [
          {
            required: true,
            message: '请选择支付方式',
            trigger: 'change'
          }
        ]
      },
      payMethodList: [
        {
          id: 'Alipay',
          name: '支付宝'
        },
        {
          id: 'WeChat',
          name: '微信'
        },
        {
          id: 'Cash',
          name: '刀乐/人民币'
        }
      ],
      title: '增加月卡'
    }
  },
  mounted() {
    const id = this.$route.query.id
    if (id) {
      this.title = '编辑月卡'
      this.getDetail(id)
    }
  },
  methods: {
    async getDetail(id) {
      try {
        const res = await getCardDetailAPI(id)
        const { personName, phoneNumber, carNumber, carBrand, cardStartDate, cardEndDate, paymentAmount, paymentMethod } = res.data
        this.carInfoForm = {
          personName,
          phoneNumber,
          carNumber,
          carBrand
        }
        this.feeForm = {
          payTime: [new Date(cardStartDate), new Date(cardEndDate)],
          paymentAmount,
          paymentMethod
        }
      } catch (error) {
        console.error('Error fetching card detail:', error)
        this.$message({
          type: 'error',
          message: '获取详情失败，请稍后再试!'
        })
      }
    },
    confirmAdd() {
      this.$refs.carInfoForm.validate(valid => {
        if (valid) {
          this.$refs.feeForm.validate(async valid => {
            if (valid) {
              // 全部校验通过
              // 参数处理
              const payload = {
                ...this.feeForm,
                ...this.carInfoForm,
                cardStartDate: this.feeForm.payTime[0],
                cardEndDate: this.feeForm.payTime[1]
              }
              delete payload.payTime
              if (this.$route.query.id) {
                // 编辑
                await updateCardAPI(payload) // 第 189 行
              } else {
                await createCardAPI(payload)
              }
              this.$router.back()
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            }
          })
        }
      })
    },
    resetForm() {
      this.$refs.carInfoForm.resetFields()
      this.$refs.feeForm.resetFields()
    }
  }
}
</script>

<style scoped lang="scss">
.add-card {
  background-color: #f4f6f8;
  height: 100vh;
  display: flex;
  flex-direction: column;

  .add-header {
    display: flex;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    background-color: #fff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    .el-page-header__content {
      font-size: 18px;
      font-weight: bold;
    }
  }

  .add-main {
    flex: 1;
    background: #f4f6f8;
    padding: 20px 130px;
    overflow-y: auto;

    .form-container {
      background-color: #fff;
      border-radius: 8px;
      margin-bottom: 20px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
        font-size: 16px;
        font-weight: bold;
        border-bottom: 1px solid #ebeef5;
      }

      .form {
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
            margin-bottom: 20px;

            .el-form-item__label {
              font-weight: normal;
            }
          }
        }
      }
    }
  }

  .add-footer {
    position: sticky;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    background: #fff;
    text-align: center;
    box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
    z-index: 10;

    .btn-container {
      justify-content: space-around;

      .el-button {
        width: 120px;
        font-size: 14px;
      }
    }
  }
}
</style>
